<template>
  <div class="">
    <div class="details_box">
      <div class="btns add_btn_top">
        <el-button
          class="btnColor"
          type="primary"
          icon="el-icon-edit-outline"
          size="mini"
          @click="dialogVisible = true"
          >编辑</el-button
        >
        <el-button
          v-permission="[2, 'button']"
          class="tb-three"
          icon="el-icon-delete"
          @click="deletesite"
          size="mini"
          >删除</el-button
        >
        <el-button
          class="tb-one"
          icon="el-icon-close"
          size="mini"
          @click.stop="turn"
          >关闭</el-button
        >
      </div>
      <div v-if="dialogVisible">
        <el-dialog
          width="750px"
          title="编辑站点类型"
          :lock-scroll="false"
          :visible.sync="dialogVisible"
          v-dialogDrag
          :close-on-click-modal="false"
        >
          <editsite
            :areaToken="areaToken"
            @submitedit="submitForm"
            @closeeditdialog="closedialogForm"
          />
        </el-dialog>
      </div>
      <Details
        :nameObj="{ key: 'name', label: '名称' }"
        :detail="areaEntiry"
        :qrCode="qrCode"
      ></Details>
    </div>
    <el-card shadow="never" style="margin-top: 8px">
      <MyTitle title="站点"></MyTitle>
      <div class="sList">
        <div class="areaBox" v-init-screen-h>
          <Empty v-if="areaList && areaList.length == 0"></Empty>
          <el-row :gutter="20" v-else>
            <el-col
              class="mb_sm"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="6"
              v-for="(area, index) in areaList"
              :key="index"
            >
              <ImgTitleContent
                :item="area"
                @handNavTo="toLinkSiteName(area.token)"
              ></ImgTitleContent>
            </el-col>
          </el-row>
        </div>
        <!-- 分页功能 -->
        <Pagination
          @pagination="pagination"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          :pageSizes.sync="pageSizes"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import Details from "@/components/Details";
import Editsite from "../opensite/editsite.vue";
import Pagination from "@/views/common/page";
import { subareas } from "@/api/gateway";
import {
  addAreasToken,
  delAreasToken,
  getQrcode,
  getDistributionAreas
} from "@/api/superlinkAreat";
import _ from "lodash";
import MyTitle from "@/components/MyTitle";
import ImgTitleContent from "@/components/ImgTitleContent";
import Empty from "@/components/Empty";
import { closeTab } from "@/views/common/js/tab-comm.js";
import { TOKEN_RULES } from "@/utils/local";
export default {
  components: {
    Empty,
    MyTitle,
    Details,
    Editsite,
    Pagination,
    ImgTitleContent
  },
  data() {
    return {
      qrCodeShow: false,
      checked: true,
      checked1: true,
      dialogAdd: false,
      dialogVisible: false,
      siteTabs: "first",
      ruleForm: {
        token: "",
        name: "",
        imageUrl: "",
        description: ""
      },
      inputname: "",
      inputvalue: "",
      rules: {
        token: TOKEN_RULES,
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 15, message: "输入格式不正确", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "请填写图片链接", trigger: "blur" }
        ]
      },
      areaList: [],
      editform: {
        token: "",
        imageUrl: "",
        name: "",
        description: ""
      },
      areaEntiry: {},
      areaToken: this.$route.query.areaToken,
      qrCode: null,
      pageNum: 1,
      pageSize: 20,
      pageSizes: [20, 50, 100, 300],
      total: 0
    };
  },
  watch: {
    $route() {
      this.areaToken = this.$route.query.areaToken;
      console.log("路由变化更新详情", this.areaToken);
      this.areatypesByToken();
      // this.getQrcode();
    }
  },
  mounted() {
    this.areatypesByToken();
    // this.getQrcode();
  },
  computed: {},
  methods: {
    mouseOver() {
      this.qrCodeShow = true;
    },
    mouseLeave() {
      this.qrCodeShow = false;
    },
    closedialogForm(flg) {
      this.dialogVisible = flg;
    },
    formatDateT(date) {
      if (date === undefined) {
        return "N/A";
      }
      return this.$moment(new Date(date)).format("YYYY-MM-DD H:mm:ss");
    },
    handleClose(done) {
      this.$confirm("确认关闭？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },

    toLinkSiteName(token) {
      if (this.$store.getters["user/isNavTo"](3)) {
        this.$router.push({ name: "sitename", query: { areaToken: token } });
      } else {
        this.$msg("您没有相关权限");
      }
    },

    turn() {
      closeTab(this.$route.fullPath, "opensiteTypeManagement");
    },
    deletesite() {
      var that = this;
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delAreasToken(this.areaToken).then(res => {
            this.$msg({
              type: "success",
              message: "删除成功!"
            });
            this.turn();
            // this.$router.push("opensiteTypeManagement");
            // this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    areatypesByToken() {
      var param = { includeContainedAreaTypes: false };
      addAreasToken(param, this.areaToken).then(res => {
        console.log("res :>> ", res.data);
        this.areaEntiry = Object.assign({}, res.data);
        this.getSiteRelate();
      });
    },

    submitForm(flg, token) {
      this.areaToken = token;
      this.dialogVisible = flg;
      console.log("token :>> ", token);
      this.toLink(token);
    },
    toLink(token) {
      // this.$router.go(0);
      this.$router.push({
        path: "/_empty",
        query: {
          data: JSON.stringify({ areaToken: token }),
          path: "thesite"
        }
      });
    },
    getQrcode() {
      var param = { responseType: "arraybuffer" };
      getQrcode(param, this.areaToken).then(res => {
        this.qrCode =
          "data:image/png;base64," +
          btoa(
            new Uint8Array(res.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
      });
    },
    getSiteRelate() {
      var that = this;
      // this.$store.getters.tenant 第一次获取的时候是字符串-无法拿到token
      var tenantToken = "";
      if (_.isString(this.$store.getters.tenant)) {
        tenantToken = JSON.parse(this.$store.getters.tenant).token;
      } else {
        tenantToken = this.$store.getters.tenant.token;
      }

      var areaTypeId = this.areaEntiry.id;
      var areaTypeToken = this.areaEntiry.token;
      var jsons = {
        // tenantToken: tenantToken,
        areaTypeToken: areaTypeToken,
        // area: "",
        page: that.pageNum,
        pageSize: that.pageSize
      };
      getDistributionAreas(jsons).then(res => {
        const { data } = res;
        that.areaList = data.results || [];
        that.total = data.numResults;
      });
    },

    handleSizeChange: function(size) {
      this.pagesize = size;
      this.getSiteRelate();
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
      this.getSiteRelate();
    },
    //分页回调
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.areatypesByToken();
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/mixin.scss";
.details_box {
  position: relative;
}

.areaBox {
  padding: 0 15px;
}
</style>
